package com.hnkywl.sts.action.kcgl;

import com.hnkywl.sts.entity.sys.Gncz;
import com.hnkywl.sts.service.kcgl.SjdjService;
import com.hnkywl.sts.service.sys.GnczService;
import com.hnkywl.sts.util.POIUtil;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: lenovo
 * Date: 13-4-30
 * Time: 上午11:34
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/kcgl/sjdj")
public class SjdjAction extends SimpleActionSupport {
    private SjdjService sjdjService;
    //功能操作
    private List<Gncz> gnczList;
    private GnczService gnczService;

    private String carno;
    private String fhrq;
    private String xsdh;
    private String htbm;
    private Integer zt;
    private int page;
    private int rows;
    private Long id;
    private String xsxt_htdh;
    private Double xsxt_price;
    private Date xsxt_fhrq;
    private File upload;
    private String sjdjIds;
    private String shzt;

    @Action("sjdj")
    public String sjdj() {
        gnczList = gnczService.findGnczByJsAndUrl(request.getServletPath());
        return SUCCESS;
    }

    @Action("sjdjList")
    public void ygList() {
        this.renderJson(this.sjdjService.findAllSjdjList(carno, fhrq, xsdh, htbm, zt, page, rows));
    }


    /**
     * 导入实际单价
     */
    @Action("sjdj_import")
    public void sjdjImport() {
        Integer row = 0;
        try {
            Workbook book = Workbook.getWorkbook(upload);
            //  获得第一个工作表对象
            Sheet sheet = book.getSheet(0);
            //获取总行数
            int rows = sheet.getRows();
            String xsxt_xsdh = "";
            String carNo = "";
            String fhrq = "";
            String hkzje;
            String jszl = "";
            String sjdj;
            String check = "0";
            List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
            for (int i = 1; i < rows; i++) { //从第2行开始导入
                row = i + 1;
                Map<String, String> map = new HashMap<String, String>();
                if (checkResult(sheet.getCell(0, i), false)) {
                    xsxt_xsdh = sheet.getCell(0, i).getContents().toString();//销售合同子项号
                    map.put("xsdh", xsxt_xsdh);
                } else {
                    check = "1";
                    break;
                }

                if (checkResult(sheet.getCell(1, i), false)) {
                    carNo = sheet.getCell(1, i).getContents().toString();//车号
                    map.put("carNo", carNo);
                } else {
                    check = "1";
                    break;
                }

                if (checkResultDate(sheet.getCell(2, i))) {
                    fhrq = sheet.getCell(2, i).getContents().toString();//发货日期
                    map.put("fhrq", fhrq);
                } else {
                    check = "1";
                    break;
                }

                if (checkResult(sheet.getCell(3, i), true)) {
                    jszl = sheet.getCell(3, i).getContents().toString();// 总重量
                    map.put("jszl", jszl);
                } else {
                    check = "1";
                    break;
                }

                if (checkResult(sheet.getCell(4, i), true)) {
                    hkzje = sheet.getCell(4, i).getContents().toString();//货款总金额
                    map.put("hkzje", hkzje);
                } else {
                    check = "1";
                    break;
                }

                if (checkResult(sheet.getCell(5, i), true)) {
                    sjdj = sheet.getCell(5, i).getContents().toString();//实际价格
                    map.put("sjdj", sjdj);
                } else {
                    break;
                }

                if (!sjdjService.checkData(xsxt_xsdh, carNo, fhrq, jszl)) {
                    check = "2";
                    break;
                }
                listMap.add(map);
            }
            if (org.apache.commons.lang3.StringUtils.equals(check, "0")) {
                this.sjdjService.saveSjdj(listMap);
                renderText("{\"statusCode\":\"200\", \"message\":\"批量导入成功！\"}");
            } else if (org.apache.commons.lang3.StringUtils.equals(check, "1")) {
                String str = "第（" + row + "）行错误，";
                renderText("{\"statusCode\":\"300\", \"message\":\"" + str + "可能为空，可能不是数字，日期应该为：2015-08-08格式！" + "\"}");
            } else {
                String str = "第（" + row + "）行错误，";
                renderText("{\"statusCode\":\"300\", \"message\":\"" + str + "根据--[合同子项号：" + xsxt_xsdh + "，车皮号：" + carNo + "，出厂日期：" + fhrq + "，总重量：" + jszl + "]---没有找到具体物资!\"}");
            }
        } catch (Exception e) {
            renderText("{\"statusCode\":\"300\", \"message\":\"数据异常：" + e.getMessage().replace("\"", " ") + "\"}");
        }
    }


    /**
     * 判断日期是否正确
     *
     * @param cell
     * @return
     */
    private boolean checkResultDate(Cell cell) {
        if (null != cell && null != cell.getContents() && org.apache.commons.lang3.StringUtils.isNotBlank(cell.getContents().toString())) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                sdf.parse(cell.getContents().toString());
                return true;
            } catch (Exception e) {

            }
        }
        return false;
    }

    /**
     * 判断格式是否正确
     *
     * @param cell
     * @param bool
     * @return
     */
    private boolean checkResult(Cell cell, boolean bool) {
        if (null != cell && null != cell.getContents() && StringUtils.isNotBlank(cell.getContents().toString())) {
            if (bool) {
                try {
                    Double dd = Double.valueOf(cell.getContents().toString());
                    if (dd <= 0) {
                        return false;
                    } else {
                        return true;
                    }
                } catch (Exception e) {

                }
            } else {
                return true;
            }
        }
        return false;
    }

    @Action("sjdj_export")
    public void sjdjExport() {
        String savePath = ServletActionContext.getRequest().getRealPath("");
        savePath = savePath + "/dc/" + "sjdj.xls";
        File file = new File(savePath);
        HSSFWorkbook wb = new HSSFWorkbook();
        try {
            FileOutputStream fout = new FileOutputStream("D:/students.xls");
            wb.write(fout);
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Action("sjdj_title_export")
    public void ygExport() {
        //第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("实际价格信息");
        POIUtil poiUtil = new POIUtil(wb);
        //设置列宽
        sheet.setDefaultRowHeightInPoints(15);
        sheet.setDefaultColumnWidth((short) 4);
        sheet.setColumnWidth((short) 0, (short) (8 * 512));
        sheet.setColumnWidth((short) 1, (short) (8 * 512));
        sheet.setColumnWidth((short) 2, (short) (8 * 1024));
        sheet.setColumnWidth((short) 3, (short) (8 * 512));
        sheet.setColumnWidth((short) 4, (short) (8 * 512));
        sheet.setColumnWidth((short) 5, (short) (8 * 512));
        //第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        //生成第一行数据
        HSSFCell xhht_zxhth = row.createCell((short) 0);
        xhht_zxhth.setCellStyle(poiUtil.createHeaderHSSFCellStyle(wb));
        xhht_zxhth.setEncoding(HSSFCell.ENCODING_UTF_16);
        xhht_zxhth.setCellValue("合同子项号");

        HSSFCell carno = row.createCell((short) 1);
        carno.setCellStyle(poiUtil.createHeaderHSSFCellStyle(wb));
        carno.setEncoding(HSSFCell.ENCODING_UTF_16);
        carno.setCellValue("车皮号");

        HSSFCell fhrq = row.createCell((short) 2);
        fhrq.setCellStyle(poiUtil.createHeaderHSSFCellStyle(wb));
        fhrq.setEncoding(HSSFCell.ENCODING_UTF_16);
        fhrq.setCellValue("发货日期(yyyy-MM-dd)");

        HSSFCell totalWeight = row.createCell((short) 3);
        totalWeight.setCellStyle(poiUtil.createHeaderHSSFCellStyle(wb));
        totalWeight.setEncoding(HSSFCell.ENCODING_UTF_16);
        totalWeight.setCellValue("总重量");

        HSSFCell totalPrice = row.createCell((short) 4);
        totalPrice.setCellStyle(poiUtil.createHeaderHSSFCellStyle(wb));
        totalPrice.setEncoding(HSSFCell.ENCODING_UTF_16);
        totalPrice.setCellValue("总价格");

        HSSFCell sjjsj = row.createCell((short) 5);
        sjjsj.setCellStyle(poiUtil.createHeaderHSSFCellStyle(wb));
        sjjsj.setEncoding(HSSFCell.ENCODING_UTF_16);
        sjjsj.setCellValue("实际单价");

        try {
            response.setContentType("application/x-download");
            String filedisplay = new String(("实际价格模板表.xls").getBytes("gb2312"), "iso8859-1");
            response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);
            wb.write(response.getOutputStream());
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
            renderText("位置异常，导出失败" + e.getMessage());
        }
    }

    /**
     * 实际单价审核
     */
    @Action("sjdj_confirm")
    public void sjdj_confirm() {
        try {
            if (StringUtils.isBlank(sjdjIds)) {
                renderText("{\"statusCode\":\"300\", \"message\":\"选择记录为空！\"}");
            } else {
                this.sjdjService.saveSjdjSh(sjdjIds, shzt);
                renderText("{\"statusCode\":\"200\", \"message\":\"审核成功！\"}");
            }
        } catch (Exception e) {
            renderText("{\"statusCode\":\"300\", \"message\":\"数据异常：" + e.getMessage().replace("\"", " ") + "\"}");
        }

    }

    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getXsxt_htdh() {
        return xsxt_htdh;
    }

    public void setXsxt_htdh(String xsxt_htdh) {
        this.xsxt_htdh = xsxt_htdh;
    }

    public SjdjService getSjdjService() {
        return sjdjService;
    }

    public Double getXsxt_price() {
        return xsxt_price;
    }

    public void setXsxt_price(Double xsxt_price) {
        this.xsxt_price = xsxt_price;
    }

    public Date getXsxt_fhrq() {
        return xsxt_fhrq;
    }

    public void setXsxt_fhrq(Date xsxt_fhrq) {
        this.xsxt_fhrq = xsxt_fhrq;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public List<Gncz> getGnczList() {
        return gnczList;
    }

    public void setGnczList(List<Gncz> gnczList) {
        this.gnczList = gnczList;
    }

    public String getCarno() {
        return carno;
    }

    public void setCarno(String carno) {
        this.carno = carno;
    }

    public String getFhrq() {
        return fhrq;
    }

    public void setFhrq(String fhrq) {
        this.fhrq = fhrq;
    }

    public String getXsdh() {
        return xsdh;
    }

    public void setXsdh(String xsdh) {
        this.xsdh = xsdh;
    }

    public String getHtbm() {
        return htbm;
    }

    public void setHtbm(String htbm) {
        this.htbm = htbm;
    }

    public Integer getZt() {
        return zt;
    }

    public void setZt(Integer zt) {
        this.zt = zt;
    }

    public String getSjdjIds() {
        return sjdjIds;
    }

    public void setSjdjIds(String sjdjIds) {
        this.sjdjIds = sjdjIds;
    }

    public String getShzt() {
        return shzt;
    }

    public void setShzt(String shzt) {
        this.shzt = shzt;
    }

    @Autowired
    public void setSjdjService(SjdjService sjdjService) {
        this.sjdjService = sjdjService;
    }

    @Autowired
    public void setGnczService(GnczService gnczService) {
        this.gnczService = gnczService;
    }
}
